# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 14:55:43 2013

@author: aponteeduarddo@gmail.com
Copyright Eduardo Aponte 2013.
"""

from mex_binder import binder_py

mx_eyelink_get_node = binder_py('mx_eyelink_get_node')
mx_eyelink_get_node.mx_c.headers = ['<eyelink.h>','"mex.h"','"utils.h"']
mx_eyelink_get_node.bindo += ['utils.o']
mx_eyelink_get_node.mx_c.code = '''
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    mwSize td[2] = {1,1};
    double *status;
    int bs;
    ELINKNODE eln;
    INT16 r;    
    
    /* Verify input arguments. */
    if(nrhs != 1 ) {
        mexErrMsgTxt("Incorrect number of inputs.");
    } else if( nlhs > 2 ) {
        mexErrMsgTxt("Too many output arguments.");
    }
    
    if ( isscalar( prhs[0] ) ){
        INT16 scalar;
        if ( returnscalar( prhs[0], &bs ) != 1 )
        mexErrMsgTxt("Complex data is not supported.");                        
    } else {
        mexErrMsgTxt("resp should be a scalar.");    
    }
    
    plhs[0] = mxCreateNumericArray( 2, td, mxDOUBLE_CLASS, mxREAL);
    status  = mxGetPr(plhs[0]);
    status[0] = (double ) eyelink_get_node( (INT16 ) bs, &eln );
    
    if (nlhs == 2) {
        int i;
        char nr[ELINKADDRSIZE];
        const char *is[] = {"elinkaddr","name"};
        
        plhs[1] = mxCreateStructMatrix(1,1,2,is);
    
    
        for (i = 0; i < ELINKADDRSIZE; i++ )
            nr[i] = (char ) eln.addr[i];
        
        mxSetField(plhs[1],0,is[0],mxCreateString( nr ));
        mxSetField(plhs[1],0,is[1],mxCreateString( eln.name ));
    }
    
    return;
}
'''

mx_eyelink_get_node.mx_c.mdoc = \
'''function [ status ] = mx_eyelink_get_node( )
%MX_EYELINK_GET_NODE Reads the responses returned by other trackers or remotes
% in response to eyelink_poll_trackers() or eyelink_poll_remotes(). It can also 
% read the tracker broadcast address and remote broadcast addresses.
%
% Parameters:
% resp 	Number of responses to read:0 gets our data, 1 get first response, 2
% gets the second response, etc. -1 to read the tracker broadcast address. -2 
% to read remote broadcast addresses.
% 
% Returns:
% 0 if OK, -1 if node response number is too high.
% data 	Pointer to buffer of ELINKNODE type, to hold name and ELINKADDR of 
% the respondent.
% 
'''
mx_eyelink_get_node.write_c()
mx_eyelink_get_node.write_m()
mx_eyelink_get_node.compile()
mx_eyelink_get_node.write_sh()

